package cn.tjad.tjad2.module.common.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;

import com.qiandian.android.base.activity.BaseActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import butterknife.BindView;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.data.bean.Pagination;

public abstract class RefreshableListActivity extends BaseActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;

    protected int startIndex;
    protected int PAGE_COUNT = 10;
    protected boolean isRefresh;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.refreshable_list_layout);
        refreshLayout.setOnRefreshLoadMoreListener(this);
    }


    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        isRefresh = false;
        requestData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        isRefresh = true;
        startIndex = 0;
        requestData();
    }

    public void onDataLoadSuccess(Pagination pagination) {
        if (pagination == null) {
            return;
        }
        startIndex = startIndex + pagination.limit;
        if (getListSize() >= pagination.totalItems) {
            refreshLayout.finishLoadMoreWithNoMoreData();
        } else {
            refreshLayout.finishLoadMore(true);
        }
        refreshLayout.finishRefresh(true);
    }

    public void onDataLoadFailed() {
        refreshLayout.finishRefresh(false);
        refreshLayout.finishLoadMore(false);
    }

    protected abstract void requestData();

    protected abstract int getListSize();
}
